// pages/userordersinfo/userordersinfo.js
const util = require('../../../../utils/util.js')
const App = getApp()
const Dialog = require('tdesign-miniprogram/dialog/index')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    order_id: 0,
    orderInfo: [],
    action: [],
    navStyle: [],
    orderStatus: 5,
    btnGroup: {
      infoOrder: '订单详情',
      delOrder: '删除订单',
      cancelOrder: '取消订单',
      goToPay: '立即支付',
      refundAfterSales: '拒绝退款|申请退款',
      viewLogistics: '查看物流',
      extendedRreceipt: '延长收货',
      confirmReceipt: '确认收货',
      viewEvaluate: '评价',
      afterSalesDetail: '售后详情|退款成功|退款中',
      anotherOrder: '再来一单'
    },
    debounceCopy: null,
    topNavImage: util.Background_base64('static/image/my_images/headerbj.png')
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      order_id: options.order_id,
      navStyle: App.globalData,
      debounceCopy: util.debounce(this.copyText, 1000)
    })
    this.getData()
  },
  // 通过操作获取按钮操作方法
  checkMedthod(e) {
    //获取键值
    let useMedthod = false
    let btnGroup = this.data.btnGroup
    Object.keys(btnGroup).forEach((k) => {
      if (useMedthod) return
      if (btnGroup[k].indexOf(e) > -1) {
        useMedthod = k
      }
    })
    return useMedthod
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getData()
  },
  //返回上一页
  navigateBack: function () {
    util.navigateBack()
  },
  //获取详情数据
  async getData() {
    const token = wx.getStorageSync('token')
    try {
      var that = this
      if (that.data.order_id > 0) {
        util
          .request(
            '/api/order/orderdetail',
            {
              order_id: that.data.order_id,
              token: token
            },
            'GET'
          )
          .then((res) => {
            var datas = res.data.data
            if (datas != '') {
              // 不同状态展示不同按钮---@dou
              var actionLs = []
              // this.data.action = ['申请退款','再来一单','确认收货'];
              let bgcJchuAll = ['立即支付', '确认收货']
              let bgcJchuNone = ['订单详情', '取消订单', '申请退款']
              datas.action.forEach((v) => {
                let useStyle = false
                if (bgcJchuAll.indexOf(v) > -1) {
                  useStyle = 'bgcJchuAll'
                } else if (bgcJchuNone.indexOf(v) > -1) {
                  useStyle = 'bgcJchuNone'
                }
                actionLs.push({
                  name: v,
                  useMtd: this.checkMedthod(v),
                  useStyle: useStyle
                })
              })
              datas.action = actionLs
              that.setData({
                orderInfo: datas,
                orderStatus: datas.status
              })
              if (datas.express_error !== '') {
                // util.showtoast({
                //     msg: datas.express_error,
                //     icon: 'error'
                // }, 1000)
              }
            } else {
              that.setData({
                orderInfo: []
              })
              wx.showToast({
                title: '暂无订单数据'
              })
            }
          })
      } else {
        wx.showToast({
          title: '参数错误'
        })
      }
    } catch (err) {
      console.log(err)
    }
  },
  //去评价
  async viewEvaluate(e) {
    if (util.isLogin() !== true) {
      return false
    }
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    var goods_id = e.currentTarget.dataset.goods_id
    var order_goods_id = e.currentTarget.dataset.order_goods_id
    wx.navigateTo({
      url: '/pages/orderpj/orderpj?order_id=' + order_id + '&goods_id=' + goods_id + '&order_goods_id=' + order_goods_id
    })
  },
  //删除订单
  async delOrder(e) {
    console.log(e)
    const dialogConfig = {
      context: this,
      title: '',
      closeOnOverlayClick: true,
      content: '确认要删除当前订单吗？',
      confirmBtn: '确定',
      cancelBtn: '取消'
    }

    Dialog.default
      .confirm(dialogConfig)
      .then(() => {
        var that = this
        var order_id = e.currentTarget.dataset.order_id
        try {
          const token = wx.getStorageSync('token')
          //请求头参数
          const header = {
            Authorization: token
          }
          const orderParams = {
            order_id,
            token
          }
          util.request('/api/order/removeOrder', orderParams, 'POST').then((res) => {
            if (res.data.code == 0) {
              that.onShow()
              util.showtoast(
                {
                  msg: '删除订单成功',
                  icon: 'success'
                },
                1000,
                '/modules/userModule/pages/userorders/userorders'
              )
            } else {
              wx.showToast({
                title: '删除订单失败'
              })
            }
          })
        } catch (err) {
          wx.showToast({
            title: err
          })
        }
      })
      .catch(() => {
        // 点击取消
      })
    if (util.isLogin() !== true) {
      return false
    }
  },
  //取消订单
  async cancelOrder(e) {
    console.log('点击取消订单')
    if (util.isLogin() !== true) {
      return false
    }
    var that = this
    var order_id = that.data.order_id
    try {
      const token = wx.getStorageSync('token')
      //请求头参数
      const header = {
        Authorization: token
      }
      const pay_type = 'WechatPay'
      const orderParams = {
        order_id,
        token
      }
      util.request('/api/order/cancelOrder', orderParams, 'POST').then((res) => {
        if (res.data.code == 0) {
          util.showtoast(
            {
              msg: '取消订单成功',
              icon: 'success'
            },
            1000,
            '/modules/userModule/pages/userorders/userorders'
          )
        } else {
          util.showtoast(
            {
              msg: '取消订单失败',
              icon: 'error'
            },
            1000
          )
        }
      })
    } catch (err) {
      wx.showToast({
        title: err
      })
    }
  },
  //获取订单号，弹出付款页面
  async goToPay(e) {
    console.log('点击支付，获取订单信息')
    if (util.isLogin() !== true) {
      return false
    }
    var that = this
    var order_no = e.currentTarget.dataset.order_no
    console.log(e, 'e')
    try {
      const token = wx.getStorageSync('token')
      //请求头参数
      const header = {
        Authorization: token
      }
      const orderParams = {
        order_no,
        token
      }
      //请求微信支付
      util.request('/api/order/wxpay', orderParams, 'POST').then((res) => {
        var data = res.data.data
        if (data.pay_state == 2) {
          that.getData()
        } else {
          if (res.data.code == 0) {
            wx.requestPayment({
              timeStamp: data.pay_params.timeStamp.toString(),
              nonceStr: data.pay_params.nonceStr,
              package: data.pay_params.package ? data.pay_params.package : '',
              signType: data.pay_params.signType,
              paySign: data.pay_params.paySign,
              // pay_type: pay_type,
              success: function (res) {
                if (res.errMsg == 'requestPayment:ok') {
                  // that.onShow()
                  // 支付成功跳转页面
                  wx.navigateTo({
                    url: '/pages/statepages/statepages?pay_state=0'
                  })
                }
              },
              fail: function (res) {
                console.log('支付失败', res)
                wx.showToast({
                  title: '支付失败'
                })
                wx.navigateTo({
                  url: '/pages/statepages/statepages?pay_state=1'
                })
              },
              complete: function (res) {
                console.log('支付完成')
                if (res.errMsg == 'requestPayment:ok') {
                  that.onShow()
                }
                return
              }
            })
          } else {
            util.showtoast(
              {
                msg: res.data.msg
              },
              1000
            )
          }
        }
      })
    } catch (error) {
      wx.showToast({
        title: '支付失败'
      })
    }
  },
  //延长收货
  async extendedRreceipt(e) {
    if (util.isLogin() !== true) {
      return false
    }
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    try {
      //判断缓存是否存在token
      const token = wx.getStorageSync('token')
      //请求头参数
      const header = {
        Authorization: token
      }
      const orderParams = {
        order_id,
        token
      }
      util.request('/api/order/extendOrder', orderParams, 'POST').then((res) => {
        if (res.data.code == 0) {
          util.showtoast(
            {
              msg: '延长收货成功',
              icon: 'success'
            },
            1000
          )
          this.onShow()
        } else {
          util.showtoast(
            {
              msg: '延长收货失败',
              icon: 'error'
            },
            1000
          )
        }
      })
    } catch (err) {
      wx.showToast({
        title: err
      })
    }
  },
  //确认收货
  async confirmReceipt(e) {
    if (util.isLogin() !== true) {
      return false
    }
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    try {
      //判断缓存是否存在token
      const token = wx.getStorageSync('token')
      //请求头参数
      const header = {
        Authorization: token
      }
      const orderParams = {
        order_id,
        token
      }
      util.request('/api/order/confirmReceipt', orderParams, 'POST').then((res) => {
        if (res.data.code == 0) {
          util.showtoast(
            {
              msg: '确认收货成功',
              icon: 'success'
            },
            1000
          )
          this.onShow()
        } else {
          util.showtoast(
            {
              msg: '确认收货失败',
              icon: 'error'
            },
            1000
          )
        }
      })
    } catch (err) {
      wx.showToast({
        title: err
      })
    }
  },
  // 查看售后详情
  async afterSalesDetail(e) {
    var order_id = e.currentTarget.dataset.order_id
    wx.navigateTo({
      url: '/pages/userorderrefund/userorderrefund?order_id=' + order_id + '&selected=10'
    })
  },
  // 订单详情
  infoOrder() {
    console.log('42342')
    wx.navigateTo({
      url: '/pages/userorders/userorders'
    })
  },
  // 再来一单
  anotherOrder() {
    if (util.isLogin() !== true) {
      return false
    }
    var that = this
    var order_id = e.currentTarget.dataset.order_id
    wx.navigateTo({
      url: '/pages/confirmcart/confirmcart?order_id=' + order_id
    })
  },
  // 点击复制
  copyText(e) {
    let eventData = arguments[0]
    let orderno = eventData.currentTarget.dataset.orderno
    wx.setClipboardData({
      data: orderno,
      success(res) {
        wx.getClipboardData({
          success(res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },
  copyOrderNo(e) {
    let eventData = e
    this.data.debounceCopy(eventData)
  }
})
